#include "gzip_utils.h"
#include <zlib.h>
#include "utils.h"

#include <iostream>
#include <string>

#include <QFile>

using namespace std;

int gzip_utils::dozip(unsigned char *in_content, int in_content_size, unsigned char *out_content, int out_content_len)
{

	memset(out_content, 0, out_content_len);
	unsigned long temp_out_content_len = out_content_len;
	compress(out_content, &temp_out_content_len, in_content, in_content_size);

	return temp_out_content_len;
}

int gzip_utils::unzip(unsigned char *in_content, int in_content_size, unsigned char *out_content, int out_content_len)
{

	memset(out_content, 0, out_content_len);
	unsigned long temp_out_content_len = out_content_len;
	uncompress(out_content, &temp_out_content_len, in_content, in_content_size);

	return temp_out_content_len;
}

int gzip_utils::unzip_file(char *in_filename, char *out_filename)
{
	//
	unsigned char szSrc[] = "test the compression and uncompression of zlib.";
	unsigned long nSrcLen = sizeof(szSrc);

	unsigned char szZip[1024] = {0};
	unsigned long nZipLen = 1024;

	FILE *pFile = fopen(in_filename, "r"); //��ȡ�ļ���ָ��
	char *pBuf;							   //�����ļ�ָ��
	fseek(pFile, 0, SEEK_END);			   //��ָ���ƶ����ļ��Ľ�β ����ȡ�ļ�����
	int len = ftell(pFile);				   //��ȡ�ļ�����
	pBuf = new char[len + 1];			   //�������鳤��
	rewind(pFile);						   //��ָ���ƶ����ļ���ͷ ��Ϊ����һ��ʼ��ָ���ƶ�����β��������ƶ����� �����
	fread(pBuf, 1, len, pFile);			   //���ļ�
	pBuf[len] = 0;						   //�Ѷ������ļ����һλ дΪ0 Ҫ��Ȼϵͳ��һֱѰ�ҵ�0��Ž���
	fclose(pFile);						   // �ر��ļ�

	compress(szZip, &nZipLen, (unsigned char *)pBuf, len);
	utils::out_file(out_filename, QByteArray(reinterpret_cast<char *>(szZip), nZipLen));

	//
	unsigned char szUnZip[10240] = {0};
	unsigned long nUnZipLen = 10240;

	pFile = fopen(out_filename, "r"); //��ȡ�ļ���ָ��
	fseek(pFile, 0, SEEK_END);		  //��ָ���ƶ����ļ��Ľ�β ����ȡ�ļ�����
	len = ftell(pFile);				  //��ȡ�ļ�����
	pBuf = new char[len + 1];		  //�������鳤��
	rewind(pFile);					  //��ָ���ƶ����ļ���ͷ ��Ϊ����һ��ʼ��ָ���ƶ�����β��������ƶ����� �����
	fread(pBuf, 1, len, pFile);		  //���ļ�
	pBuf[len] = 0;					  //�Ѷ������ļ����һλ дΪ0 Ҫ��Ȼϵͳ��һֱѰ�ҵ�0��Ž���
	fclose(pFile);					  // �ر��ļ�

	uncompress(szUnZip, &nUnZipLen, (unsigned char *)pBuf, len);
	utils::out_file(out_filename, QByteArray(reinterpret_cast<char *>(szUnZip), nUnZipLen));

	//
	cout << "Src:" << szSrc << ", len:" << nSrcLen << endl;
	cout << "Zip:" << szZip << ", len:" << nZipLen << endl;
	cout << "UnZip:" << szUnZip << ", len:" << nUnZipLen << endl;

	return true;
}
